<template>
	<view v-if="showPopup" class="uni-popup" @touchmove.stop.prevent="clear">
		<my-transition :mode-class="['fade']" :styles="maskClass" :show="showTrans" @click="onTap" />
		<my-transition :mode-class="ani" :styles="transClass" :duration="duration" :show="showTrans" @click="onTap">
			<view class="uni-popup__wrapper-box" @click.stop="clear" >
				<view class="uni-tip-buy relative">
					<view class="title-box flex">
						<!-- 盲盒名称 -->
						<view class="name sl1" v-if="JSON.stringify(blindList)!=='{}'">{{blindList.name}}</view>
						<!-- 规格 -->
						<view class="ggtext sl1" v-if="JSON.stringify(blindList)!=='{}'">{{blindList.description}}</view>
						<!-- 盲盒图片 -->
						<image class="boximg" :src="blindList.imageUrl" v-if="JSON.stringify(blindList)!=='{}'"></image>
						<!-- 价格和数量 -->
						<view class="price-number">
							<view class="left">
								<text class="text" v-if="JSON.stringify(blindList)!=='{}'">￥{{blindList.newprice}}</text>
							</view>
							<view class="right" v-if="JSON.stringify(ceshiObj)!=='{}'">x{{ceshiObj[boxChoiceIndex].count}}</view>
						</view>
						<!-- 横线 -->
						<view class="xian"></view>
					</view>
					<!-- 开盒方式 -->
					<view class="mode-box">
						<view class="left">
							<text class="qwa">开盒方式</text>
						</view>
						<view class="right" v-if="JSON.stringify(blindList)!=='{}'">
							<view class="item" v-for="(item,index) in blindList.openTypeList" :key="index" @click="boxChang(index)">
								<p class="title sl1">{{item.name}}</p>
									<p class="price">
										<text>￥{{item.newprice}}</text>
									</p>
								<image class="pp" src="/static/index/xzchange.png" v-show="boxChoiceIndex==index"></image>
							</view>
						</view>
					</view>
					<!-- 连抽优惠 -->
					<view class="hb-box flex" v-if="JSON.stringify(ceshiObj)!=='{}'&&boxChoiceIndex>0||blindList.discountBox==1">
						<text class="left">连抽优惠</text>
						<view class="right flex padeight">
							<text class="yi">{{ceshiObj[boxChoiceIndex].newcutPrice}}</text>
						</view>
					</view>
					<!-- 余额 -->
					<view class="hb-box flex">
						<text class="left">余额</text>
						<view class="right flex padeight">
							<text class="yi">{{userMoneyNew}}</text>
						</view>
					</view>
					<!-- 合计和确认支付 -->
					<view class="price-box flex">
						<view class="left flex">
							<text class="a">合计：</text>
							<view class="b">
								<text>￥{{(totalPrice*1)<0?'0.00':totalPrice}}</text>
							</view>
						</view>
						<view class="right" @click="getUserPrice">立即支付</view>
					</view>
					<!-- 协议 -->
					<view class="xy-box flex" @click="checkYear">
						<image class="radio" :src="yearCheck?'/static/xz.png':'/static/ysxyx.png'"></image>
						<view class="text">我已满18岁，且已阅读并同意<text @click.stop="gowebview('https://home.miaokaikeji.com/web/agreement/serviceAgreement.html')" style="color: #333333;">《服务协议》</text></view>
					</view>
					<view :style="{height: sourceType=='index'?'25rpx':'60rpx'}"></view>
				</view>
			</view>
		</my-transition>
	</view>
</template>

<script>
	import myTransition from '../my-transition/my-transition.vue'
	import { priceInteger,debounce } from "@/utils";
	export default {
		name: 'MyBuy',
		components: {
			myTransition
		},
		props: {
			// 开启动画
			animation: {
				type: Boolean,
				default: true
			},
			// 弹出层类型，可选值，top: 顶部弹出层；bottom：底部弹出层；center：全屏弹出层
			type: {
				type: String,
				default: 'bottom'
			},
			// maskClick
			maskClick: {
				type: Boolean,
				default: true
			},
			boxId:{
				type: String,
				default: ''
			},
			sourceType:{
				type: String,
				default: 'index'
			},
			propChoseIndex:{
				type: Number,
				default: 1
			}
		},
		data() {
			return {
				duration: 300,
				ani: [],
				showPopup: false,
				showTrans: false,
				maskClass: {
					'position': 'fixed',
					'bottom': 0,
					'top': 0,
					'left': 0,
					'right': 0,
					'backgroundColor': 'rgba(0, 0, 0, 0.6)'
				},
				transClass: {
					'position': 'fixed',
					'left': 0,
					'right': 0,
				},
				yearCheck:this.$cookie.get('yearCheck')?this.$cookie.get('yearCheck'):false, //满18岁勾选协议控制
				boxChoiceIndex: this.$cookie.get('boxChoiceIndex')?this.$cookie.get('boxChoiceIndex'):0, //开盒方式（index）
				blindList: [],
				userMoney:0,
				userMoneyNew:0,
				ceshiObj:{},
			}
		},
		watch: {
			propChoseIndex: {
                handler: function(newVal) {
					this.boxChoiceIndex=newVal;
					this.$cookie.set('boxChoiceIndex',newVal)
                },
            },
			boxId: {
			    handler: function(newVal) {
					this.getBlindList();
			    },
			},
			type: {
				handler: function(newVal) {
					switch (this.type) {
						case 'top':
							this.ani = ['slide-top']
							this.transClass = {
								'position': 'fixed',
								'left': 0,
								'right': 0,
							}
							break
						case 'bottom':
							this.ani = ['slide-bottom']
							this.transClass = {
								'position': 'fixed',
								'left': 0,
								'right': 0,
								'bottom': 0
							}
							break
						case 'center':
							this.ani = ['zoom-out', 'fade']
							this.transClass = {
								'position': 'fixed',
								/* #ifndef APP-NVUE */
								'display': 'flex',
								'flexDirection': 'column',
								/* #endif */
								'bottom': 0,
								'left': 0,
								'right': 0,
								'top': 0,
								'justifyContent': 'center',
								'alignItems': 'center'
							}

							break
					}
				},
				immediate: true
			}
		},
		created() {
			if (this.animation) {
				this.duration = 300
			} else {
				this.duration = 0
			}
			this.getBlindList();
			this.getUserMoney();
		},
		computed:{
			//前端计算得到的总价
			totalPrice:function(){
				return priceInteger(this.blindList.openTypeList[this.boxChoiceIndex].price - this.userMoney);
			}
		},
		methods: {
			checkYear(){
				this.yearCheck=!this.yearCheck;
				this.$cookie.set('yearCheck',this.yearCheck);
			},
			clear(e) {
				// TODO nvue 取消冒泡
				e.stopPropagation()
			},
			open() {
				this.showPopup = true
				this.getUserMoney();
				this.$nextTick(() => {
					clearTimeout(this.timer)
					this.timer = setTimeout(() => {
						this.showTrans = true
					}, 50);
				})
				this.$emit('change', {
					show: true
				})
			},
			close(type) {
				this.showTrans = false
				this.$nextTick(() => {
					clearTimeout(this.timer)
					this.timer = setTimeout(() => {
						this.$emit('change', {
							show: false
						})
						this.showPopup = false
					}, 300)
				})
			},
			onTap() {
				if (!this.maskClick) return
				this.close()
				this.$emit('maskClick');
			},
			getBlindList() {
				this.$HTTP({
					method: 'GET',
					url: 'shopServer/box/getBoxDetail/'+this.boxId,
					data: {
						time: Date.parse(new Date())
					}
					// header:'form'
				}).then(res => {
					res.newprice=priceInteger(res.price);
					res.goodsList.forEach((item, index) => {
						item.newprice = priceInteger(item.price);
					})
					res.openTypeList.forEach((item, index) => {
						item.newprice = priceInteger(item.price);
						item.newcutPrice = priceInteger(item.cutPrice);
					})
					// 判断前端存储没有匹配到的情况重置为第一个
					if(this.$cookie.get('boxChoiceIndex')>res.openTypeList.length-1){
						this.boxChoiceIndex=0;
					}else{
						this.boxChoiceIndex=this.$cookie.get('boxChoiceIndex')?this.$cookie.get('boxChoiceIndex'):0;
					}
					this.discountBox=res.discountBox;
					this.blindList = res;
					this.ceshiObj=res.openTypeList;
					
				}).catch(err => {
					console.log(err);
				});
			},
			gowebview(url){
				uni.navigateTo({
					url: '/pages/index/webview?url='+url
				});
			},
			// 切换盒子购买
			boxChang(index){
				if(this.boxChoiceIndex==index){
					return;
				}
				this.boxChoiceIndex=index;
				this.$cookie.set('boxChoiceIndex',index)
			},
			getUserMoney(){
				this.$HTTP({
					method: 'GET',
					url: 'shopServer/user/getUserInfo',
					data: {
						time: Date.parse(new Date())
					}
					// header: 'form'
				}).then(res => {
					this.userMoneyNew=priceInteger(res.balance);
					this.userMoney=res.balance;
				}).catch(err => {
					console.log(err);
				});
			},
			getUserPrice:debounce(function(){
				if(!this.yearCheck){
					this.$api.msg('请先勾选用户协议');
					return;
				}
				const {aplus_queue} = window;
				aplus_queue.push({
				 action: 'aplus.record',
				  arguments: ['openBox','1']
				});
				// 判断余额足不足
				this.$HTTP({
					method: 'GET',
					url: 'shopServer/user/getUserInfo',
					data: {
						time: Date.parse(new Date())
					}
					// header: 'form'
				}).then(res => {
					if(Math.trunc(this.totalPrice*100)>0){
							// 余额不足跳转充值
							this.$routerTo.navigateTo({
								path: '/pages/index/recharge'
							});
					}else{
						// 余额足执行抽奖
						aplus_queue.push({
						 action: 'aplus.record',
						  arguments: [this.blindList.openTypeList[this.boxChoiceIndex].id,'1']
						});
						this.goLuckDraw();
					}
				}).catch(err => {
					console.log(err);
				});
			},1000),
			goLuckDraw(){
				this.close()
				if(this.blindList.openTypeList[this.boxChoiceIndex].count==1){
					// 单抽
					if(this.sourceType=='index' || this.sourceType=='blindDetail'){
						this.$routerTo.navigateTo({
							path: '/pages/index/luckDraw?id='+this.blindList.id
						});
					}else if(this.sourceType=='LotteryResults'){
						this.$routerTo.redirectTo({
							path: '/pages/index/luckDraw?id='+this.blindList.id
						});
					}
				}
				else if(this.blindList.openTypeList[this.boxChoiceIndex].count<=5){
					// 多抽
					if(this.sourceType=='index' || this.sourceType=='blindDetail'){
						this.$routerTo.navigateTo({
							path: '/pages/index/luckDrawMore?id='+this.boxId+'&type=' + this.blindList.openTypeList[this.boxChoiceIndex].id+'&count='+this.blindList.openTypeList[this.boxChoiceIndex].count
						});
					}else if(this.sourceType=='LotteryResults'){
						this.$routerTo.redirectTo({
							path: '/pages/index/luckDrawMore?id='+this.boxId+'&type='+ this.blindList.openTypeList[this.boxChoiceIndex].id+'&count='+this.blindList.openTypeList[this.boxChoiceIndex].count
						});
					}
				}
				else if(this.blindList.openTypeList[this.boxChoiceIndex].count>5 ){
					// 大于五个或者跳过动画
					this.$HTTP({
						method: 'POST',
						url: 'shopServer/box/openBox',
						data: {
							boxId: this.boxId,
							openTypeId: this.blindList.openTypeList[this.boxChoiceIndex].id, //开盒类型ID
							time: Date.parse(new Date())
						},
						header:'form'
					}).then(res => {
						res.forEach((item, index) => {
							item.newprice = priceInteger(item.price);
							item.newrecyclePrice = priceInteger(item.recyclePrice);
						})
						if(this.sourceType=='index' || this.sourceType=='blindDetail'){
							this.$routerTo.navigateTo({
								path: '/pages/index/LotteryResults?data='+JSON.stringify(res)+'&boxId='+this.boxId
							});
						}else if(this.sourceType=='LotteryResults'){
							this.$routerTo.redirectTo({
								path: '/pages/index/LotteryResults?data='+JSON.stringify(res)+'&boxId='+this.boxId
							});
						}
					}).catch(err => {
						console.log(err);
					});
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	.uni-popup {
		position: fixed;
		/* #ifdef H5 */
		top: var(--window-top);
		/* #endif */
		/* #ifndef H5 */
		top: 0;
		/* #endif */
		bottom: 0;
		left: 0;
		right: 0;
		/* #ifndef APP-NVUE */
		z-index: 999;
		/* #endif */
	}

	.uni-popup__mask {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: rgba(0, 0, 0, 0.4);
		opacity: 0;
	}

	.mask-ani {
		transition-property: opacity;
		transition-duration: 0.2s;
	}

	.uni-top-mask {
		opacity: 1;
	}

	.uni-bottom-mask {
		opacity: 1;
	}

	.uni-center-mask {
		opacity: 1;
	}

	.uni-popup__wrapper {
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
		position: absolute;
	}

	.top {
		top: 0;
		left: 0;
		right: 0;
		transform: translateY(-500px);
	}

	.bottom {
		bottom: 0;
		left: 0;
		right: 0;
		transform: translateY(500px);
	}

	.center {
		/* #ifndef APP-NVUE */
		display: flex;
		flex-direction: column;
		/* #endif */
		bottom: 0;
		left: 0;
		right: 0;
		top: 0;
		justify-content: center;
		align-items: center;
		transform: scale(1.2);
		opacity: 0;
	}

	.uni-popup__wrapper-box {
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
		position: relative;
	}

	.content-ani {
		/* transition: transform 0.3s;
 */
		transition-property: transform, opacity;
		transition-duration: 0.2s;
	}


	.uni-top-content {
		transform: translateY(0);
	}

	.uni-bottom-content {
		transform: translateY(0);
	}

	.uni-center-content {
		transform: scale(1);
		opacity: 1;
	}
	// 购买弹窗
	.uni-tip-buy {
		width: 100%;
		// height: 1062rpx;
		background: #FFFFFF;
		border-radius: 40rpx 40rpx 0rpx 0rpx;
		position: relative;
		z-index: 100;
		.title-box{
			width: 100%;
			height: 386rpx;
			background-image: url('https://home.miaokaikeji.com/web/applet/newimg/poptopbg.png');
			background-size: 100% 100%;
			position: relative;
			box-sizing: border-box;
			padding: 0 32rpx;
			
			.name{
				width: 270rpx;
				position: absolute;
				left: 32rpx;
				top: 75rpx;
				font-size: 44rpx;
				font-weight: bold;
				color: #FFFFFF;
			}
			.ggtext{
				width: 270rpx;
				position: absolute;
				left: 32rpx;
				top: 145rpx;
				font-size: 30rpx;
				font-weight: bold;
				color: #FFFFFF;
			}
			.boximg{
				width: 400rpx;
				height: 400rpx;
				position: absolute;
				right: 32rpx;
				top: -138rpx;
			}
			.price-number{
				width: calc(100% - 64rpx);
				position: absolute;
				left: 32rpx;
				bottom: 75rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				.left{
					font-size: 28rpx;
					font-weight: bold;
					color: #333333;
					display: flex;
					align-items: center;
					.text{
						font-size: 36rpx;
					}
					image{
						margin-right: 5rpx;
						width: 32rpx;
						height: 32rpx;
					}
				}
				.right{
					font-size: 32rpx;
					color: #333333;
				}
			}
			.xian{
				width: calc(100% - 64rpx);
				height: 2rpx;
				background: #000000;
				opacity: 0.1;
				position: absolute;
				left: 32rpx;
				bottom: 45rpx;
			}
		}
		.mode-box{
			width: 100%;
			box-sizing: border-box;
			padding: 0 0 0 27rpx;
			transform: translateY(-20rpx);
			.left{
				width: 100%;
				box-sizing: border-box;
				padding:0 25rpx 0 5rpx;
				margin-bottom: 4rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				.qwa{
					font-size: 32rpx;
					color: #24323B;
				}
				.tgdh{
					align-items: center;
					.text{
						font-size: 26rpx;
						color: #24323B;
					}
					.radio{
						width: 30rpx;
						height: 30rpx;
						margin-left: 10rpx;
					}
				}
			}
			.right{
				width: 100%;
				.item:nth-child(4){
					width: 97% !important;
					background-image: url('https://home.miaokaikeji.com/web/applet/newimg/xzbg1.png') !important;
					.title{
						text-align: center;
					}
					.price{
						justify-content: center;
					}
				}
				.item:nth-child(5){
					width: 97% !important;
					background-image: url('https://home.miaokaikeji.com/web/applet/newimg/xzbg1.png') !important;
					.title{
						text-align: center;
					}
					.price{
						justify-content: center;
					}
				}
				.item{
					width: 232rpx;
					height: 137rpx;
					background-image: url('https://home.miaokaikeji.com/web/applet/newimg/xzbg.png');
					background-size: 100% 100%;
					margin-left: 5rpx;
					margin-top: 10rpx;
					display: inline-block;
					box-sizing: border-box;
					padding: 20rpx 0 0 35rpx;
					position: relative;
					.pp{
						position: absolute;
						right: -20rpx;
						top: -10rpx;
						width: 101rpx;
						height: 101rpx;
					}
					.title{
						font-size: 32rpx;
						font-weight: bold;
						color: #B60014;
					}
					.price{
						width: 100%;
						font-size: 24rpx;
						font-weight: bold;
						color: #FFFFFF;
						margin-top: 7rpx;
						display: flex;
						align-items: center;
						.qqqa{
							width: 24rpx;
							height: 24rpx;
							margin-right: 5rpx;
						}
					}
				}
			}
		}
		.hb-box{
			width: 100%;
			box-sizing: border-box;
			padding: 0 32rpx 20rpx 32rpx;
			justify-content: space-between;
			align-items: center;
			.left{
				font-size: 32rpx;
				color: #24323B;
			}
			.padeight{
				padding-right: 30rpx;
			}
			.right{
				align-items: center;
				box-sizing: border-box;
				.yi{
					font-size: 30rpx;
					color: #FF2643;
				}
				.wei{
					font-size: 30rpx;
					color: #999999;
				}
				image{
					width: 16rpx;
					height: 27rpx;
					margin-left: 14rpx;
				}
			}
		}
		.text11{
			width: 100%;
			font-size: 26rpx;
			color: #FF2643;
			box-sizing: border-box;
			padding: 0 32rpx;
		}
		.xy-box{
			width: 100%;
			justify-content: center;
			align-items: center;
			margin-top: 25rpx;
			.radio{
				width: 30rpx;
				height: 30rpx;
			}
			.text{
				font-size: 26rpx;
				color: #CCCCCC;
				margin-left: 10rpx;
			}
		}
		.price-box{
			width: 100%;
			box-sizing: border-box;
			padding: 15rpx 32rpx 0 32rpx;
			align-items: center;
			justify-content: space-between;
			.left{
				align-items: center;
				.a{
					font-size: 28rpx;
					color: #24323B;
				}
				.b{
					font-size: 36rpx;
					font-weight: bold;
					color: #24323B;
					display: flex;
					align-items: center;
					image{
						width: 32rpx;
						height: 32rpx;
						margin-right: 5rpx;
					}
				}
			}
			.right{
				width: 329rpx;
				height: 88rpx;
				background: #FF9416;
				box-shadow: 0rpx 10rpx 20rpx 1rpx rgba(255,148,22,0.43);
				border-radius: 48rpx;
				line-height: 88rpx;
				text-align: center;
				font-size: 32rpx;
				color: #FFFFFF;
			}
		}
	}
</style>